<template>
  <PageWrapper>
    <a-card :bordered="false" class="mb-3 proCard">
      <a-space align="center">
        <a-input-group style="width: 380px">
          <a-input
            :style="{ width: '100%' }"
            v-model="params.title"
            clearable
            placeholder="请输入标题"
            @keyup.enter="reloadTable"
          />
          <a-button type="primary" @click="reloadTable">
            <template #icon>
              <a-icon>
                <SearchOutlined />
              </a-icon>
            </template>
            查询
          </a-button>
        </a-input-group>
      </a-space>
    </a-card>
    <a-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        row-key="postId"
        ref="basicTableRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        virtual-scroll
      >
        <template #tableTitle>
          <a-space align="center">
            <a-button type="primary" @click="openCreateDrawer">
              <template #icon>
                <a-icon>
                  <FileAddOutlined />
                </a-icon>
              </template>
              添加
            </a-button>
            <a-button type="primary" status="success" @click="handelExportArticle">
              <template #icon>
                <a-icon>
                  <ExportOutlined />
                </a-icon>
              </template>
              导出
            </a-button>
            <a-button type="primary" status="warning" @click="handelImportArticle">
              <template #icon>
                <a-icon>
                  <ImportOutlined />
                </a-icon>
              </template>
              导入
            </a-button>
          </a-space>
        </template>
      </BasicTable>
    </a-card>

    <createModal
      ref="createModalRef"
      :title="drawerTitle"
      :roleList="roleData"
      @change="reloadTable"
    />
    <ImportModal ref="importModalRef" @change="reloadTable" />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { BasicTable, TableAction, BasicColumn } from '@/components/Table';
  import { articleList, deleteArticle, exportArticle } from '@/api/article/index';
  import { FileAddOutlined, SearchOutlined, ExportOutlined, ImportOutlined } from '@vicons/antd';
  import createModal from './CreateModal.vue';
  import ImportModal from './ImportModal.vue';
  import { columns } from './columns';
  import { downloadFile } from '@/utils';

  const basicTableRef = ref();
  const rowKeys = ref([]);
  const rowKeysName = ref([]);
  const tableData = ref();
  const createModalRef = ref();
  const importModalRef = ref();
  const drawerTitle = ref('添加文章');
  const roleData = ref([]);
  const exportBtn = ref(false);

  let messageReactive: any = null;

  const params = reactive({
    title: '',
  });

  const actionColumn: BasicColumn = reactive({
    width: 175,
    title: '操作',
    key: 'action',
    fixed: 'right',
    align: 'center',
    render({ record }) {
      return h(TableAction as any, {
        actions: [
          {
            label: '删除',
            popConfirm: {
              content: '您确定要删除吗？',
              okText: '确定',
              cancelText: '取消',
              onOk: handleDelete.bind(null, record),
            },
          },
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
          },
        ],
      });
    },
  });

  const loadDataTable = async (res) => {
    const result = await articleList({ ...params, ...res });
    tableData.value = result.list;
    return result;
  };

  function handelImportArticle() {
    importModalRef.value.showModal();
  }

  function removeMessage() {
    if (messageReactive) {
      messageReactive.close();
      messageReactive = null;
    }
  }

  function handelExportArticle() {
    exportBtn.value = true;
    messageReactive = Message.loading('系统正在导出，请稍等');
    exportArticle()
      .then((res) => {
        try {
          if (res.status === 200 && res.data) {
            downloadFile(res);
            removeMessage();
            Message.success('导出成功');
          }
        } catch {
          removeMessage();
          Message.error('系统异常，导出失败');
        }
        exportBtn.value = false;
      })
      .catch(() => {
        exportBtn.value = false;
      });
  }

  function onCheckedRow(keys) {
    rowKeys.value = keys;
    rowKeysName.value = tableData.value
      .filter((item) => {
        return keys.includes(item.id);
      })
      .map((item) => {
        return item.username;
      })
      .join('，');
  }

  function reloadTable() {
    basicTableRef.value.reload();
  }

  function openCreateDrawer() {
    drawerTitle.value = '添加文章';
    const { showModal } = createModalRef.value;
    showModal();
  }

  function handleEdit(record) {
    const { showModal } = createModalRef.value;
    showModal(record.id);
  }

  function handleDelete(record: Recordable) {
    deleteArticle({ articleId: record.id }).then(() => {
      Message.success('删除成功');
      reloadTable();
    });
  }
</script>

<style lang="less" scoped></style>
